package com.huangmb.anymark.app.fragment.add;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.widget.*;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.*;
import com.huangmb.androidlib.utils.Logger;
import com.huangmb.anymark.app.R;
import com.huangmb.anymark.app.activity.base.AppBaseActivity;
import com.huangmb.anymark.app.api.BaseApi;
import com.huangmb.anymark.app.api.FileApi;
import com.huangmb.anymark.app.api.UserMarkerApi;
import com.huangmb.anymark.app.app.AnyMarkApplication;
import com.huangmb.anymark.app.fragment.BaseMapFragment;
import com.huangmb.anymark.app.model.Category;
import com.huangmb.anymark.app.model.UserMarker;
import com.huangmb.anymark.app.utils.Locator;
import com.huangmb.common.utils.StringUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author hmb
 * @version 1.0
 * @since 2016/4/26 22:09
 */
public class AddPlaceFragment extends BaseMapFragment implements TextWatcher {
    private static final String TAG = AddPlaceFragment.class.getSimpleName();
    private static final int REQUEST_CODE_GET_PICTURE = 1;
    private static final int MENU_ITEM_ID_OK = 1;
    private ImageView mCoverImageView;
    private EditText mTitleEt;
    private EditText mContentEt;
    private TextInputLayout mTitleInputLayout;
    private TextInputLayout mContentInputLayout;
    private TextView mAddress;
    private Bitmap mCoverBitmap;
    private int mCategoryId = 1;
    private Spinner mCategorySpinner;
    private final List<Category> mCategoryList = new ArrayList<>();
    private Uri mCoverUri;
    private Marker mCenterMarker;

    private MenuItem mMenuOK;
    private UploadManager mUploadManager = AnyMarkApplication.getInstance().getUploadManager();
    private boolean isModifyState = false;
    private UserMarker mMarker;
    private boolean canCommit = false;

    private ProgressBar mProgressBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.d(TAG, "onCreate");
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_add_place, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Logger.d(TAG, "onViewCreated");
        getActionBar().setTitle(R.string.menu_add_place);
        mProgressBar = getProgressbar();
        MapView mapView = (MapView) view.findViewById(R.id.map);
        setUpMapView(mapView, savedInstanceState);

        mTitleEt = (EditText) view.findViewById(R.id.title);
        mContentEt = (EditText) view.findViewById(R.id.content);
        mCoverImageView = (ImageView) view.findViewById(R.id.cover);
        mTitleInputLayout = (TextInputLayout) view.findViewById(R.id.title_layout);
        mContentInputLayout = (TextInputLayout) view.findViewById(R.id.content_layout);
        mAddress = (TextView) view.findViewById(R.id.address);
        mCategorySpinner = (Spinner) view.findViewById(R.id.category);

        ImageButton addImageBtn = (ImageButton) view.findViewById(R.id.btn_add_img);
        addImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, REQUEST_CODE_GET_PICTURE);
            }
        });


        final String[] category = {"生活", "美食", "购物", "景点"};
        ArrayAdapter<String> mSpinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, category);
        mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCategorySpinner.setAdapter(mSpinnerAdapter);
        mCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        mCategoryId = 1;
                        break;
                    case 1:
                        mCategoryId = 2;
                        break;
                    case 2:
                        mCategoryId = 4;
                        break;
                    case 3:
                        mCategoryId = 5;
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        if (getArguments() != null) {
            mMarker = getArguments().getParcelable("marker");
        }
        if (mMarker != null) {
            isModifyState = true;
            double latitude = mMarker.getLatitude();
            double longitude = mMarker.getLongitude();
            LatLng pos = new LatLng(latitude, longitude);
            getAMap().moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 18));
            mCenterMarker = getAMap().addMarker(new MarkerOptions().position(pos));

            mTitleEt.setText(mMarker.getTitle());
            mContentEt.setText(mMarker.getInfo());
            mAddress.setText(mMarker.getAddress());
            mCategoryId = mMarker.getCategory().getId();
            mCategorySpinner.setVisibility(View.GONE);
            canCommit = true;
        } else {
            isModifyState = false;
            mMarker = new UserMarker();
            Locator.startLocationOnce(new Locator.LocationListener() {
                @Override
                public void onLocationChanged(@NonNull AMapLocation aMapLocation) {
                    double latitude = aMapLocation.getLatitude();
                    double longitude = aMapLocation.getLongitude();
                    LatLng pos = new LatLng(latitude, longitude);
                    getAMap().moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 15));
                    mCenterMarker = getAMap().addMarker(new MarkerOptions().position(pos));
                    queryAddress(pos);
                }

                @Override
                public void onFail(AMapLocation aMapLocation) {
                    toast("定位失败");
                    Logger.d(TAG, "定位失败");
                }
            });
        }

        mTitleEt.addTextChangedListener(this);
        mContentEt.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String title = mTitleEt.getText().toString();
        String content = mContentEt.getText().toString();
        if (StringUtils.isBlank(title)) {
            mTitleInputLayout.setError("标题不能为空");
            canCommit = false;
        } else if (title.length() > 12) {
            mTitleInputLayout.setError("长度不能超过12个字");
            canCommit = false;
        } else {
            mTitleInputLayout.setError(null);
            if (!StringUtils.isBlank(content)) {
                mContentInputLayout.setError(null);
                canCommit = true;
            } else {
                mContentInputLayout.setError("内容不能为空");
                canCommit = false;
            }
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        super.onCameraChange(cameraPosition);
        if (mCenterMarker != null) {
            mCenterMarker.setPosition(cameraPosition.target);
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        super.onCameraChangeFinish(cameraPosition);
        if (!isNeedIgnoreCameraChange()) {
            queryAddress(cameraPosition.target);
        }
    }

    private void queryAddress(LatLng latLng) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(getContext());
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
            }

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i == 1000) {
                    RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
                    //省略了省市的地理位置
                    String address = regeocodeAddress.getFormatAddress()
                            .replace(regeocodeAddress.getProvince(), "")
                            .replace(regeocodeAddress.getCity(), "");
                    Logger.d(TAG, "查询到位置 ：" + address);
                    mAddress.setText(address);

                }
            }

        });
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude), 100, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_GET_PICTURE) {
            if (resultCode == Activity.RESULT_OK) {
                mCoverUri = data.getData();
                Logger.d(TAG, "封面 uri:" + mCoverUri.toString());
                ContentResolver resolver = getContext().getContentResolver();
                try {

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    options.inSampleSize = 1;
                    BitmapFactory.decodeStream(resolver.openInputStream(mCoverUri), null, options);
                    int width = options.outWidth;
                    int height = options.outHeight;
                    options.inSampleSize = width / 720;
                    Logger.d(TAG, "sampleSize " + options.inSampleSize);
                    options.inJustDecodeBounds = false;
                    mCoverBitmap = BitmapFactory.decodeStream(resolver.openInputStream(mCoverUri), null, options);
                    Logger.d(TAG, "高度" + mCoverBitmap.getHeight());
                    mCoverImageView.setImageBitmap(mCoverBitmap);
                } catch (FileNotFoundException e) {
                    Logger.d(TAG, "未得到图片", e);
                }
            } else {
                Logger.d(TAG, "未得到图片");
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        mMenuOK = menu.add(Menu.NONE, MENU_ITEM_ID_OK, Menu.NONE, "提交").setIcon(R.drawable.ic_ok);
        mMenuOK.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        Logger.d(TAG, "onCreateOptionsMenu");

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ID_OK) {
            commitForm();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void commitForm() {
        if (mCategoryId == -1) {
            toast("请选择类别");
            return;
        }

        if (!canCommit) {
            toast("表单填写完整");
            return;
        } else {
            toast("提交表单");
        }

        mProgressBar.setVisibility(View.VISIBLE);
        if (mCoverBitmap != null) {
            final String key = UUID.randomUUID().toString();
            FileApi.getPutPolicy(key, new BaseApi.AbsListener() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    //result即为上传凭证
                    uploadImage(key, result);
                }
            });
        } else {
            createMarker(null);
        }


    }

    /**
     * 上传封面图片
     *
     * @param key   用于表示图片的键值，可用uuid生成
     * @param token 上传凭证，通过FileApi获得
     */
    private void uploadImage(String key, String token) {
        toast("正在上传图片");
        mProgressBar.setIndeterminate(false);
        mProgressBar.setMax(100);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        mCoverBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        final byte[] data = outputStream.toByteArray();
        mUploadManager.put(data, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                createMarker(key);
            }
        }, new UploadOptions(null, null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                mProgressBar.setProgress((int) (percent * 100));
            }
        },null));
    }

    private void createMarker(String image) {
        mProgressBar.setIndeterminate(true);

        LatLng latLng = getAMap().getCameraPosition().target;
        String title = mTitleEt.getText().toString();
        String content = mContentEt.getText().toString();
        mMarker.setTitle(title);
        mMarker.setInfo(content);
        mMarker.setLatitude(latLng.latitude);
        mMarker.setLongitude(latLng.longitude);
        mMarker.setAddress(mAddress.getText().toString());
        mMarker.setCoverImage(image);

        mMarker.setCategory(new Category(mCategoryId));
        if (isModifyState) {
            UserMarkerApi.modify(mMarker, new BaseApi.AbsListener() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    toast("修改成功");
                    mProgressBar.setVisibility(View.GONE);
                    getActivity().onBackPressed();
                }

                @Override
                public void onFail(int errorCode, String errorMessage) {
                    super.onFail(errorCode, errorMessage);
                    toast("修改失败");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        } else {
            UserMarkerApi.create(mMarker, new BaseApi.AbsListener() {
                @Override
                public void onSuccess(String result) {
                    Logger.d(TAG, result);
                    toast("创建成功");
                    mProgressBar.setVisibility(View.GONE);
                    //回到首页
                    getActivity().finish();
                }

                @Override
                public void onFail(int errorCode, String errorMessage) {
                    toast("创建失败");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        }

    }

}
